package com.yonyou.rabbitmq.service;

import com.yonyou.rabbitmq.common.MessageConstants;
import com.yonyou.rabbitmq.common.enums.SiteEnum;
import com.yonyou.rabbitmq.producer.ReliableRabbitTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.InvalidParameterException;

@Service
public class BaseProducerService {

    @Resource(name = MessageConstants.GF_RABBIT_TEMPLATE)
    ReliableRabbitTemplate gfTemplate;

    @Resource(name = MessageConstants.ZW_RABBIT_TEMPLATE)
    ReliableRabbitTemplate zwTemplate;

    public void sendMsgStr(String exchange, String routingKey, String message, CorrelationData correlationData, String tenantId){
        Message msg = MessageBuilder.withBody(message.getBytes()).build();
        sendMsg(exchange,routingKey,msg,correlationData,tenantId);
    }

    public void sendMsg(String exchange, String routingKey, Message message, CorrelationData correlationData,String tenantId){
        ReliableRabbitTemplate template = getTemplateByTenantId(tenantId);
        template.send(exchange,routingKey,message,correlationData,tenantId);
    }

    public void sendDelayStr(String routingKey,String message,long delayTimes,CorrelationData correlationData,String tenantId){
        Message msg = MessageBuilder.withBody(message.getBytes()).build();
        sendDelay(routingKey,msg,delayTimes,correlationData,tenantId);
    }

    public void sendDelay(String routingKey,Message message,long delayTimes,CorrelationData correlationData,String tenantId) {
        ReliableRabbitTemplate template = getTemplateByTenantId(tenantId);
        message.getMessageProperties().setHeader(MessageConstants.X_DELAY, delayTimes);
        template.send(MessageConstants.DELAYED_EXCHANGE_NAME, routingKey,message,correlationData,tenantId);
    }

    public ReliableRabbitTemplate getTemplateByTenantId(String tenantId){
        ReliableRabbitTemplate template = null;
        if(SiteEnum.GF.getKey().equals(tenantId)){
            template = gfTemplate;
        }else if(SiteEnum.ZW.getKey().equals(tenantId)){
            template = zwTemplate;
        }else{
            throw new InvalidParameterException("未找到对应租户！");
        }
        return template;
    }
}
